package com.airline.controller;

import com.airline.dto.ApiResponse;
import com.airline.entity.Flight;
import com.airline.service.FlightService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/flights")
@RequiredArgsConstructor
public class FlightController {
    private final FlightService flightService;

    // 初始化航班数据
    @PostMapping("/init")
    public ApiResponse<String> initFlights() {
        try {
            flightService.initFlights();
            return ApiResponse.success("航班数据初始化成功");
        } catch (Exception e) {
            return ApiResponse.error("初始化失败: " + e.getMessage());
        }
    }

    // 获取所有航班
    @GetMapping
    public ApiResponse<List<Flight>> getAllFlights() {
        List<Flight> flights = flightService.getAllFlights();
        return ApiResponse.success("查询成功", flights);
    }

    // 根据ID获取航班
    @GetMapping("/{id}")
    public ApiResponse<Flight> getFlightById(@PathVariable Long id) {
        Optional<Flight> flight = flightService.getFlightById(id);
        return flight.map(f -> ApiResponse.success("查询成功", f))
                .orElse(ApiResponse.error("航班不存在"));
    }

    // 创建航班
    @PostMapping
    public ApiResponse<Flight> createFlight(@RequestBody Flight flight) {
        try {
            Flight savedFlight = flightService.createFlight(flight);
            return ApiResponse.success("航班创建成功", savedFlight);
        } catch (Exception e) {
            return ApiResponse.error("创建失败: " + e.getMessage());
        }
    }

    // 测试方法
    @GetMapping("/ping")
    public String ping() {
        return "Flight PONG";
    }

    @GetMapping("/test")
    public String test() {
        return "Flight test works!";
    }
}